﻿package {
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.text.TextField;
	import flash.events.KeyboardEvent;

	/**
	 * Main demo
	 * @author wilson
	 */
	public class Main extends Sprite {
		
		public function Main():void {
			if (stage) {
				init();
			} else {
				addEventListener(Event.ADDED_TO_STAGE, init);
			}
		}
		private function init(e:Event = null):void {
			// set stage property
			this.stage.align = StageAlign.TOP_LEFT;
			this.stage.scaleMode = StageScaleMode.NO_SCALE;
			this.stage.stageWidth = 640;
			this.stage.stageHeight = 80;

			//add to  stage
			out_textBoard = new outtext();
			addChild(out_textBoard);
			
			in_textBoard= new intext();
			addChild(in_textBoard);
			
			
			// simulate as a button
			cle_buttom= new Sprite();
			cle_buttom.graphics.beginFill(0x3399FF);
			cle_buttom.graphics.drawRect(0, 0, 80, 30);
			cle_buttom.graphics.endFill();
			cle_buttom.x=300 , cle_buttom.y=250;
			
			b_lable=new TextField();
			b_lable.text="清空";
			b_lable.x=25;
			addChild(cle_buttom);
			cle_buttom.addChild(b_lable);
			
			// listene to change
			in_textBoard.addEventListener(MouseEvent.CLICK,clean);  //only clean in_text
			in_textBoard.addEventListener(KeyboardEvent.KEY_UP, outInfo);
			
			//all clean
			cle_buttom.addEventListener(MouseEvent.CLICK,cleanall);
			
			stage.addEventListener(KeyboardEvent.KEY_DOWN,getkeycode);  //check charcode
			stage.addEventListener(KeyboardEvent.KEY_DOWN,lock);

		}
		private function outInfo(str:String):void{
			out_textBoard.showInfo(in_textBoard.in_text.text);
		}
		
		//clean
		private function clean(e:MouseEvent):void {
			in_textBoard.in_text.text=" ";
		}
		
		private function cleanall(e:MouseEvent):void {
			if(judge){    									//if judge is true then only clean in_text
				in_textBoard.in_text.text=" ";
			}else{
				in_textBoard.in_text.text=" ";
				out_textBoard.showInfo(" ");
				}
		}
		
		//locking
		private function lock(e:KeyboardEvent):void{
				if(e.keyCode == 97){  
				in_textBoard.removeEventListener(KeyboardEvent.KEY_UP, outInfo);
				judge=!judge;  
			}
		}
		
		//check charcode and add listener 
		private function getkeycode(e:KeyboardEvent):void{
				//key = e.keyCode;
				if (judge == false) {
					in_textBoard.addEventListener(KeyboardEvent.KEY_UP, outInfo);
				}

				//trace("按鍵"+String.fromCharCode(e.charCode)+"\t字元值"+e.keyCode);
		}
		
		private var out_textBoard:outtext;
		private var in_textBoard:intext;
		private var b_lable:TextField;
		private var cle_buttom:Sprite;
		private var key:int;
		private var judge:Boolean;

	}
}